'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Search, Plus, Edit, Trash2, AlertCircle } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';

interface Category {
  categoryId: number;
  categoryName: string | null;
  categoryCode: string | null;
  categoryField: number | null;
  commodityCount: number;
}

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [categoryToDelete, setCategoryToDelete] = useState<number | null>(null);
  const [newCategory, setNewCategory] = useState({
    categoryName: '',
    categoryCode: '',
    categoryField: 0
  });

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/categories');
      
      if (!response.ok) {
        throw new Error('获取分类数据失败');
      }
      
      const data = await response.json();
      setCategories(data.categories);
    } catch (error) {
      console.error('获取分类数据失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleEditCategory = async () => {
    if (!currentCategory) return;
    
    try {
      if (!currentCategory.categoryName) {
        alert('分类名称不能为空');
        return;
      }

      const response = await fetch(`/api/categories?id=${currentCategory.categoryId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          categoryName: currentCategory.categoryName,
          categoryCode: currentCategory.categoryCode,
          categoryField: currentCategory.categoryField
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新分类失败');
      }

      setIsEditDialogOpen(false);
      setCurrentCategory(null);
      fetchCategories();
    } catch (error) {
      console.error('更新分类失败:', error);
      alert(error instanceof Error ? error.message : '更新分类失败');
    }
  };

  const handleCreateCategory = async () => {
    try {
      if (!newCategory.categoryName) {
        alert('分类名称不能为空');
        return;
      }

      const response = await fetch('/api/categories', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newCategory),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '创建分类失败');
      }

      // 重置表单并关闭对话框
      setNewCategory({
        categoryName: '',
        categoryCode: '',
        categoryField: 0
      });
      setIsDialogOpen(false);
      
      // 重新获取分类列表
      fetchCategories();
    } catch (error) {
      console.error('创建分类失败:', error);
      alert(error instanceof Error ? error.message : '创建分类失败');
    }
  };

  const handleDeleteCategory = async (categoryId: number) => {
    setCategoryToDelete(categoryId);
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteCategory = async () => {
    if (!categoryToDelete) return;
    
    try {
      const response = await fetch(`/api/categories?id=${categoryToDelete}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除分类失败');
      }

      // 关闭对话框并重新获取分类列表
      setIsDeleteDialogOpen(false);
      setCategoryToDelete(null);
      fetchCategories();
    } catch (error) {
      console.error('删除分类失败:', error);
      alert(error instanceof Error ? error.message : '删除分类失败');
    }
  };

  // 过滤分类
  const filteredCategories = categories.filter(category => 
    category.categoryName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    category.categoryCode?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">分类管理</h1>
        <p className="text-muted-foreground">查看和管理商品分类信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">分类列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索分类..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  添加分类
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加新分类</DialogTitle>
                  <DialogDescription>
                    请填写以下信息创建新的商品分类
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="categoryName" className="text-right">
                      分类名称
                    </Label>
                    <Input
                      id="categoryName"
                      value={newCategory.categoryName}
                      onChange={(e) => setNewCategory({...newCategory, categoryName: e.target.value})}
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="categoryCode" className="text-right">
                      分类编码
                    </Label>
                    <Input
                      id="categoryCode"
                      value={newCategory.categoryCode}
                      onChange={(e) => setNewCategory({...newCategory, categoryCode: e.target.value})}
                      className="col-span-3"
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="categoryField" className="text-right">
                      分类领域
                    </Label>
                    <select
                      id="categoryField"
                      value={newCategory.categoryField}
                      onChange={(e) => setNewCategory({...newCategory, categoryField: parseInt(e.target.value)})}
                      className="col-span-3 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      <option value="0">二手物品</option>
                      <option value="1">论坛</option>
                    </select>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsDialogOpen(false)}>取消</Button>
                  <Button onClick={handleCreateCategory}>创建</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>

            <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>编辑分类</DialogTitle>
                  <DialogDescription>
                    请修改以下分类信息
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="editCategoryName" className="text-right">
                      分类名称
                    </Label>
                    <Input
                      id="editCategoryName"
                      value={currentCategory?.categoryName || ''}
                      onChange={(e) => currentCategory && setCurrentCategory({
                        ...currentCategory,
                        categoryName: e.target.value
                      })}
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="editCategoryCode" className="text-right">
                      分类编码
                    </Label>
                    <Input
                      id="editCategoryCode"
                      value={currentCategory?.categoryCode || ''}
                      onChange={(e) => currentCategory && setCurrentCategory({
                        ...currentCategory,
                        categoryCode: e.target.value
                      })}
                      className="col-span-3"
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="editCategoryField" className="text-right">
                      分类领域
                    </Label>
                    <select
                      id="editCategoryField"
                      value={currentCategory?.categoryField || 0}
                      onChange={(e) => currentCategory && setCurrentCategory({
                        ...currentCategory,
                        categoryField: parseInt(e.target.value)
                      })}
                      className="col-span-3 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      <option value="0">二手物品</option>
                      <option value="1">论坛</option>
                    </select>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>取消</Button>
                  <Button onClick={handleEditCategory}>保存</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>分类名称</TableHead>
                  <TableHead>分类编码</TableHead>
                  <TableHead>分类领域</TableHead>
                  <TableHead>商品数量</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCategories.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center h-24">未找到匹配的分类</TableCell>
                  </TableRow>
                ) : (
                  filteredCategories.map((category) => (
                    <TableRow key={category.categoryId}>
                      <TableCell>{category.categoryId}</TableCell>
                      <TableCell className="font-medium">{category.categoryName || '-'}</TableCell>
                      <TableCell>{category.categoryCode || '-'}</TableCell>
                      <TableCell>
                        <Badge variant={category.categoryField === 0 ? "default" : "secondary"}>
                          {category.categoryField === 0 ? '二手物品' : '论坛'}
                        </Badge>
                      </TableCell>
                      <TableCell>{category.commodityCount}</TableCell>
                      <TableCell className="text-right">
                        <Button 
                          variant="ghost" 
                          size="icon"
                          onClick={() => {
                            setCurrentCategory(category);
                            setIsEditDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="icon"
                          onClick={() => handleDeleteCategory(category.categoryId)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 删除确认对话框 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个分类吗？如果该分类下有商品，可能无法删除。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setCategoryToDelete(null)}>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteCategory}>确认删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}